//这个demo用来学习atmic_flag c++11自旋锁的使用
#include <iostream>
#include <atomic>
#include <unistd.h>
#include <thread>
std::atomic_flag lock = ATOMIC_FLAG_INIT;//初始化，此时lock处于clear状态

void f(int n)
{
    //如果原子变量被锁住，返回1,没有返回0并加锁
    while(lock.test_and_set()) //获取锁的状态
    {
        std::cout << "waiting..." <<std::endl;
    }

    std::cout << "thread " << n << "is starting working." << std::endl;
}

void g(int n)
{
    sleep(3);
    std::cout<<"thread " << n << "is going to clear the flag." <<std::endl;
    //进行了clear
    lock.clear();
}
int main()
{
    //进行了set
    lock.test_and_set();
    std::thread t1(f,1);
    std::thread t2(g,2);

    t1.join();
    t2.join();
    return 0;
}

